const wx_server_sdk = require('wx-server-sdk');

wx_server_sdk.init({
    env: 'cloud-test-167cc2'
});

const db = wx_server_sdk.database();

var nowTime = getBeijingTime();

//每2分钟自动运行
async function funcMain(event, context) {
    context.callbackWaitsForEmptyEventLoop = false; //针对node 10.15版本的设置,避免一些函数跑空造成拖延时间
    nowTime = getBeijingTime();

    var productKey = event.productKey,
        deviceName = event.deviceName,
        deviceSecret = event.deviceSecret,
        payload = {
            t: 1,
            h: 0,
            f: 1,
            p: 0,
            w: 0,
        }
    return await setDeviceProperties(productKey, deviceName, deviceSecret, payload);
    // callback(null, { generalAlarm, generalError });
}

//根据设备信息,计算生成联网通讯的验证密码
function gnrtMqttUsernamePassword_aliyun(opts) {
    nowTime = getBeijingTime();

    var options = {
        productKey: opts.productKey,
        deviceName: opts.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2)
    }
    let keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${options[key]}`);
    });
    const contentStr = list.join('');

    const crypto = require('./hex_hmac_sha1');
    opts.password = crypto.hex_hmac_sha1(opts.deviceSecret, contentStr);

    opts.protocol = opts.protocol || 'mqtt';
    var secureMode = (opts.protocol === 'mqtts') ? 2 : 3;
    opts.clientId = `${options.clientId}|securemode=${secureMode},signmethod=hmacsha1,timestamp=${options.timestamp}|`;
    opts.username = `${opts.deviceName}&${opts.productKey}`;

    opts.port = opts.port || 1883;
    opts.regionId = opts.regionId || 'cn-shanghai';
    opts.host = opts.host || `${opts.productKey}.iot-as-mqtt.${opts.regionId}.aliyuncs.com`;
    return opts;
}

async function setDeviceProperties(productKey, deviceName, deviceSecret, payload) {
    const asyncMqtt = require('async-mqtt');

    // 1. 设备身份信息
    var options = gnrtMqttUsernamePassword_aliyun({ productKey, deviceName, deviceSecret });

    var client = asyncMqtt.connect(options);

    console.log("连接参数:", options);
    var setResult = {
        errMsg: 'ok',
    }
    try {
        var topic = '/sys/' + options.productKey + '/' +
            options.deviceName + '/thing/event/property/post';

        var composeMsgData = function(msg) {
            var payloadJson = {
                id: getNowTimestamp() * 100 + Math.floor(Math.random() * 1000),
                version: "1.0",
                params: msg,
                method: "thing.event.property.post"
            }

            payloadJson = JSON.stringify(payloadJson);
            // console.log("组成的 payload Json " + payloadJson)
            return payloadJson;
        }

        await client.publish(topic, composeMsgData(payload), { qos: 1 });
        await client.end();
        console.log("关闭连接:" + options.deviceName);
    } catch (ex) {
        setResult.errMsg = 'error'
        console.log("连接物联网平台出错", ex.stack);
    }
    return setResult;
}

function getNowTimestamp() {
    return new Date().getTime();
}

function getBeijingTime(localTs) {
    var time_ts = localTs;
    if (typeof(localTs) != 'number' || localTs == 0) {
        time_ts = getNowTimestamp();
    }

    var time = tsToDateStr(time_ts);

    return {
        ts: time_ts,
        time,
        date: new Date(time_ts),
    };
}

function tsToDateStr(ts_para) {
    //2020-06-14 20:49:59
    //未在此弥补时差
    var time_ts = new Date(ts_para + 8 * 3600000);

    // console.log('用于制作中文的ts', time_ts.getTime());

    var time_str = time_ts.getFullYear() + '-';

    if ((time_ts.getMonth() + 1) < 10) {
        time_str += '0';
    }
    time_str += '' + (time_ts.getMonth() + 1) + '-';


    if (time_ts.getDate() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getDate() + ' ';


    if (time_ts.getHours() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getHours() + ':';

    if (time_ts.getMinutes() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getMinutes() + ':';

    if (time_ts.getSeconds() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getSeconds(); // + ':' + time_ts.getMilliseconds();

    return time_str;
}

exports.main = funcMain